package com.fh.controller.building.customer;
import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.entity.system.User;
import com.fh.service.building.RecordService;
import com.fh.service.building.customer.CustomerService;
import com.fh.util.Const;
import com.fh.util.DateUtil;
import com.fh.util.JSONHelper;
import com.fh.util.PageData;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.PrintWriter;
import java.util.*;

import static com.fh.controller.system.tools.GetDatalayui.getLData;
import static com.fh.controller.system.tools.GetDatalayui.getPData;

/**
 *Created by songyinan on 2017/9/27.
 */

@Controller
@RequestMapping(value ="/customer")
public class CustomerController extends BaseController{

    @Resource(name = "customerService")
    private CustomerService customerService;

    @Resource(name = "recordService")
    private RecordService recordService;


    /**
     *新增
     */
    @RequestMapping(value="/save")
    @ResponseBody
    public PageData save(){
        logBefore(logger, "新增Customer");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try{
            PageData u = new PageData();//新增

            String Customer_ID = this.get32UUID();
            String time = new DateUtil().getTime();

            u.put("ID", Customer_ID);    //主键
            u.put("CREATE_ID", user.getUSER_ID()); //创建时间
            u.put("CREATE_DATE", time); //创建时间
            u.put("SORT", 0); //排序
            u.put("IS_DEL", 0); //是否删除

            u.put("TYPE",pd.get("data1[TYPE]"));

            u.put("TRADE",pd.get("data1[TRADE]"));

            u.put("COMPANY",pd.get("data1[COMPANY]"));

            u.put("FIR_VISIT_DATE",pd.get("data1[FIR_VISIT_DATE]"));

            u.put("CONTACT",pd.get("data1[CONTACT]"));

            u.put("CONTACT_TEL",pd.get("data1[CONTACT_TEL]"));

            u.put("LEG_REN",pd.get("data1[LEG_REN]"));

            u.put("LEG_TEL",pd.get("data1[LEG_TEL]"));

            u.put("SIGN_REN",pd.get("data1[SIGN_REN]"));

            u.put("SIGN_TEL",pd.get("data1[SIGN_TEL]"));

            u.put("BUSS_CODE",pd.get("data1[BUSS_CODE]"));

            u.put("ADDRESS",pd.get("data1[ADDRESS]"));

            u.put("QUA_CUS",pd.get("data1[QUA_CUS]"));

            u.put("ALL_WAY",pd.get("data1[ALL_WAY]"));

            u.put("DEMAN_AREA",pd.get("data1[DEMAN_AREA]"));

            u.put("FOLLOW_DATE",pd.get("data1[FOLLOW_DATE]"));

            u.put("LEAS_CONS",pd.get("data1[LEAS_CONS]"));

            u.put("CUS_STATUS",pd.get("data1[CUS_STATUS]"));

            u.put("CUS_INFO",pd.get("data1[CUS_INFO]"));
            customerService.save(u);

            //获得jsonArray的第一个元素
            JSONArray jsonArray = JSONArray.fromObject(pd);
            Object o2 = jsonArray.get(0);
            JSONObject jsonObject2 = JSONObject.fromObject(o2);
            //JSONHelper.json2Map(jsonObject2.get("sendData[DATA]").toString());
            Map map2 = JSONHelper.json2Map(jsonObject2.get("sendData[DATA]").toString());
            Set<Object> keySet2 = map2.keySet();
            //有了Set集合。就可以获取其迭代器。
            Iterator<Object> it2 = keySet2.iterator();
            while (it2.hasNext()) {
                Object key = it2.next();
                //有了键可以通过map集合的get方法获取其对应的值。
                Object value = (Object) map2.get(key);
                List<PageData> list2 = (List<PageData>) JSONArray.toList(JSONArray.fromObject(value.toString()), PageData.class);
                for (PageData stu : list2) {
                    PageData customer_room = new PageData();//物业价格
                    customer_room.put("ID", this.get32UUID());//物业设置主键
                    customer_room.put("IS_DEL", 0); //是否删除
                    customer_room.put("SORT", 0); //排序
                    customer_room.put("CREATE_ID", user.getUSER_ID()); //用户ID
                    customer_room.put("CREATE_DATE", time); //创建时间
                    customer_room.put("CUSTOMER_ID",Customer_ID );//customerID
                    customer_room.put("ROOM_ID", stu.get("ROOM_ID").toString());//价格
                    customerService.savecustomer(customer_room);
                }
            }


            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        }catch(Exception e){
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /**
     * 客戶数据展示（json）
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object json(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<>();
        List<PageData> varList;
        String datalayui = null;
            try {
            //测试分页 导出为layui的json数据
            pd = this.getPageData();
            getPData(page, pd);//必填 2参
            varList = customerService.list(page);    //列出Building列表
            datalayui = getLData(page, varList);//必填 2参
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }
    /**
     * 租客 数据展示（json）
     */
    @RequestMapping(value = "/zhlist")
    @ResponseBody
    public Object zhlist(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<>();
        List<PageData> varList;
        String datalayui = null;
        try {
            //测试分页 导出为layui的json数据
            pd = this.getPageData();
            getPData(page, pd);//必填 2参
            varList = customerService.zhlist(page);    //列出Building列表
            datalayui = getLData(page, varList);//必填 2参
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }


  /* *//**
     * 跳到修改-新
     * @param
     * @return
     *//*
    @RequestMapping(value = "/FindById")
    @ResponseBody
    public PageData listone() {
        logBefore(logger, "Customer列表");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        try {
            PageData list = roleService.findbyid(pd);
            res.put("data", list);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }
*/

    /**
     * 修改
     * @return
     * @throws Exception
     *//*

    @RequestMapping(value="/edit")
    public ModelAndView edit() throws Exception{
        logBefore(logger, "修改Customer");
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        customerService.edit(pd);
        mv.addObject("msg","success");
        mv.setViewName("save_result");
        return mv;
    }*/


    /**
     * 角色修改-新
     * @return
     */
    @RequestMapping(value = "/editx")
    @ResponseBody
    public PageData editx() {
        logBefore(logger, "新增Business");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        String CREATE_ID = user.getUSER_ID();
        try {
            customerService.edit(pd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /**
     * 删除客户
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public PageData delete() {
        PageData res = new PageData();
        PageData pd = this.getPageData();
        try {
            pd = this.getPageData();
            customerService.delete(pd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


  /*  @RequestMapping(value = "/goEdit")
    public ModelAndView goEdit() {
        logBefore(logger, "去修改Customer页面");
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try {
            pd = customerService.findById(pd);    //根据ID读取
            mv.setViewName("build/building/building_edit");
            mv.addObject("msg", "edit");
            mv.addObject("pd", pd);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }*/

    /**
     * 通过ID获取客户管理详情信息
     */
    @RequestMapping(value = "/info")
    @ResponseBody
    public PageData info() {
        logBefore(logger, "Customer详情");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            PageData data = customerService.findById(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }



    /**
     * 通过ID获取租户详情信息
     */
    @RequestMapping(value = "/infotenant")
    @ResponseBody
    public PageData infotenant() {
        logBefore(logger, "租户管理详情");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            PageData data = customerService.findtenantById(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /**
     * 字典表中的所属行业信息
     */
    @RequestMapping(value = "/listdictionary")
    @ResponseBody
    public PageData listdictionary() {
        logBefore(logger, "dictionary列表");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        try {
            List<PageData> list = customerService.listdictionary(pd);
            res.put("data", list);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /**
     * 删除租户信息
     */
    @RequestMapping(value = "/deltenant")
    @ResponseBody
    public PageData deldictionary() {
        logBefore(logger, "deltenantdeltenant（删除租户信息）");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        try {
            //customerService.deltenant(pd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /**
     * 修改
     */
    @RequestMapping(value = "/edittenant")
    @ResponseBody
    public PageData edittenant() {
        logBefore(logger, "修改edittenant（修改租户信息）");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            customerService.edittenant(pd);
            customerService.edittenantSIGNER(pd);//修改签订人
            //保存操作记录
            PageData add = new PageData();
            add.put("ID", this.get32UUID());    //主键
            add.put("IS_DEL", 0); //是否删除
            add.put("SORT", 0); //排序
            add.put("CREATE_ID", user.getUSER_ID()); //创建用户
            add.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            add.put("OPERA_TIME", new DateUtil().getTime()); //创建时间
            add.put("DETAILS", "修改租户基本信息");//提交合同
            add.put("TENANT_ID",pd.get("ID")); //创建时间
            add.put("OPERATOR", user.getNAME());
            recordService.save(add);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

}
